const Koa = require('koa')
const path = require('path')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-generic-session')
const redisStore = require('koa-redis')
const koaStatic = require('koa-static') // 静态资源目录
const { REDIS_CONF } = require('./config/db')
const { isprod } = require('./utils/env')
const { SESSION_SECRET_KEY } = require('./config/secretkeys')

// 路由
const atAPIRouter = require('./routes/api/blog-at')
const squareAPIRouter = require('./routes/api/blog-square')
const profileAPIRouter = require('./routes/api/blog-profile')
const homeAPIRouter = require('./routes/api/blog-home')
const blogViewRouter = require('./routes/view/blog')
const utilAPIRouter = require('./routes/api/utils')
const userViewRouter = require('./routes/view/user')
const userAPIRouter = require('./routes/api/user')
const errorViewRouter = require('./routes/view/error')

// error handler
// 路由错误的配置项
let onerrorConf = {}
if(isprod){  // 线上 跳转 错误页
  onerrorConf = {
    redirect: '/error'
  }
}
onerror(app, onerrorConf)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(koaStatic(__dirname + '/public'))
// 设置可以访问用户上传图片
// app.use(koaStatic(__dirname + '../uploadFiles'))
app.use(koaStatic(path.join(__dirname, '..', 'uploadFiles')))

app.use(views(__dirname + '/views', {
  extension: 'ejs',
}))

// session 配置
app.keys = [SESSION_SECRET_KEY]
app.use(session({
  key: 'captern.sid',  // cookie name  默认是 'koa.sid'
  prefix: 'captern:sess:',  //  redis key  的前缀， 默认 是 'koa:sess'
  cookie: {
    path: '/',
    httpOnly: true,  // 仅服务端修改
    maxAge: 24 * 60 * 60 * 1000  // 毫秒
  },
  // ttl: 24 * 60 * 60 * 1000,   // redis 的过期时间, 默认和 cookid 的过期时间相同，可以暂时不写
  store: redisStore({
    all: `${REDIS_CONF.host}:${REDIS_CONF.port}`
  })
}))


// logger
// 中间件的演示，手写 log 功能
// app.use(async (ctx, next) => {
//   const start = new Date()
//   await next()
//   const ms = new Date() - start
//   console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
// })

// routes

app.use(atAPIRouter.routes(), atAPIRouter.allowedMethods()) // 个人空间
app.use(squareAPIRouter.routes(), squareAPIRouter.allowedMethods()) // 个人空间
app.use(profileAPIRouter.routes(), profileAPIRouter.allowedMethods()) // 个人空间
app.use(homeAPIRouter.routes(), homeAPIRouter.allowedMethods()) // 博客首页 API
app.use(blogViewRouter.routes(), blogViewRouter.allowedMethods())
app.use(utilAPIRouter.routes(), utilAPIRouter.allowedMethods())
app.use(userViewRouter.routes(), userViewRouter.allowedMethods()) // 用户 View 路由
app.use(userAPIRouter.routes(), userAPIRouter.allowedMethods()) // 用户 API 路由
// 404 路由注册在最下面
app.use(errorViewRouter.routes(), errorViewRouter.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
